<?php

/**
 * @filename CateAction.class.php 
 * @encoding UTF-8 
 * @author yuzhiyuan <307090870@qq.com>
 * @copyright copyright 2013 (c) Emagsoftware Technology Co., Ltd. All Rights reserved.
 * @license ……
 * @datetime 2013-6-22  17:43:30
 * @version 1.0
 * @Description
  */
class CateAction extends BaseAction {
    public function index(){
        import('Class.Cate',APP_PATH);
        $cdb = new CateModel();
        $list = $cdb->order('sort asc')->select();
     //   $list = Cate::getChildId($list, 1);
     //   p($list);
        $list = Cate::unlimitedForLevel($list);
     //   $list = Cate::unlimitedForLayer($list);
        $this->assign('cates', $list);
        $this->display();
    }
    public function add(){
        import('Class.Cate',APP_PATH);
        $this->p_id = I('p_id',0,'intval');
        $cdb = new CateModel();
        $list = $cdb->order('sort asc')->select();
        $list = Cate::unlimitedForLevel($list);
  //      p($list);
        $this->assign('cates', $list);
        $this->display();
    }
    public function doAdd(){
        if(!(IS_POST)) halt ('页面不存在！');
        $cdb = new CateModel();
        if(!$cdb->create()){
            $this->error($cdb->getError());           
        }        
        if($cdb->add()){
           $this->success('添加成功！',U(GROUP_NAME . '/Cate/index'));
        }else{
           $this->error('添加失败！');
        }

    }
    
    public function sort(){
        $cbd = M('Cate');
        foreach($_POST as $k => $v){
            $cbd->where("id = " . $k)->setField('sort',$v);
        }
        $this->redirect(GROUP_NAME . '/Cate/index');
        
    }
    
    public function del(){
        $id = I('id',0,intval);
        $cbd = M('Cate');
        $has_chld = $cbd->where("p_id = ".$id)->count();
        if($has_chld > 0){
            $this->error('该分类下有子分类，不可删除！');
        }
        if($cbd->where("id = ".$id)->delete()){
            $this->success('删除成功！');
        }else{
            $this->error('删除失败！');
        }
    }
    
    
    public function edit(){
        import('Class.Cate',APP_PATH);
        $c_id = I('id',0,intval);
        $cdb = new CateModel();
        $list = $cdb->order('sort asc')->select();
        
        $list = Cate::unlimitedForLevel($list);
        $res = $cdb->where("id = ".$c_id)->find();
        if(empty($res)){
            $this->error('该记录不存在！');
        }
        $this->assign('list', $list);
        $this->assign('cate', $res);
        $this->display();
    }
    
    public function doEdit(){
        $id = I('id',0,intval);
        $cdb = new CateModel();
        if($cdb->create()){
            if($cdb->where("id = ".$id)->save()){
                $this->success('更新成功！');
            }else{
                $this->error('更新失败！');
            }
        }else{
            $this->error($cdb->getError());
        }
    }
}